import React, { Fragment } from 'react';
import { connect } from 'dva';
import { Table, Card, Form, Popconfirm, message, Button } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from '../../styles/Manage.less';

@Form.create()
@connect(({ resource, loading }) => ({
  resource,
  loading: loading.models.resource,
}))
class PermissionApprove extends React.Component {
  // 表格字段
  columns = [
    { title: '申请人', dataIndex: 'nickname' },
    { title: '申请资源', dataIndex: 'applyResources' },
    {
      title: '操作',
      dataIndex: 'option',
      render: (text, record) => (
        <Fragment>
          <Button mask={['EDIT']}>
            <Popconfirm
              placement="top"
              title="确定同意？"
              onConfirm={() => this.handleApprove(record, true)}
            >
              <a>同意</a>
            </Popconfirm>
          </Button>
          <Button mask={['EDIT']}>
            <Popconfirm
              placement="top"
              title="确定拒绝？"
              onConfirm={() => this.handleApprove(record, false)}
            >
              <a>拒绝</a>
            </Popconfirm>
          </Button>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'resource/fetchApplies',
    });
  }

  // 审批操作处理
  handleApprove = ({ userId }, pass) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'resource/approve',
      payload: {
        userId,
        pass,
      },
      callback: () => {
        message.success('审批成功');
        // 重载数据
        this.reloadData();
      },
    });
  };

  // 重新加载数据
  reloadData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'resource/fetchApplies',
      payload: {},
    });
  };

  render() {
    const {
      resource: { applies },
      loading,
    } = this.props;
    return (
      <PageHeaderWrapper title="资源审批" content="审批本部门用户的申请">
        <Card bordered={false}>
          <div className={styles.Manage}>
            <Table
              loading={loading}
              dataSource={applies}
              columns={this.columns}
              rowKey={record => record.userId}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default PermissionApprove;
